package team.seekers.hula.auth.service;

import com.alibaba.fastjson.JSON;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import team.seekers.hula.common.entity.UserSessionDTO;
import team.seekers.hula.common.entity.enums.user.RoleEnum;
import team.seekers.hula.common.entity.result.ApiException;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.Date;

/**
 * @author Godc
 * @description
 */
public class MindUtils {

    /**
     * 获得当前登录用户的userId
     */
    public static String getUserId() {
        return getUser().getId();
    }

    public static Boolean isLogin() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userSessionDTOStr = request.getHeader(UserSessionDTO.HEADER_KEY);
        UserSessionDTO userByToken = JSON.parseObject(userSessionDTOStr, UserSessionDTO.class);
        return userByToken != null;
    }

    public static UserSessionDTO getUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userSessionDTOStr = request.getHeader(UserSessionDTO.HEADER_KEY);
        UserSessionDTO userByToken = JSON.parseObject(userSessionDTOStr, UserSessionDTO.class);
        if(userByToken == null){
            throw new ApiException().code(401).message("您还未登录！");
        }
        return userByToken;
    }

    /**
     * 判断当前用户是不是管理员
     */
    public static Boolean isAdmin(){
        return getUser().getRole().equals(RoleEnum.MONITOR.getName());
    }

    //获取两个日期间的天数差
    public static float differentDaysByMillisecond(Date date1, Date date2) {
        System.out.println(date1+"        "+date2);
        long diffSeconds = date2.getTime() - date1.getTime();
        long diffHour = diffSeconds / (1000 * 3600);
        float diffDay = (float) diffHour / 24;
        float floatDay = decimalFormat("0.00", diffDay);
        return floatDay;
    }
    //日期格式转化
    public static float decimalFormat(String pattern, double value) {
        return Float.parseFloat(new DecimalFormat(pattern).format(value));
    }

    public static boolean isTrueType(Integer type) {
        if(type != null){
            if( type >0 && type<5){
                return true;
            }
        }
        return false;
    }
}
